import os
import platform
import multiprocessing
from trunk.lib.uplink import Uplink

def check():
    if not os.path.exists('config/key.xml'):
        print 'no key found, registering node'
        register()

def register(*args, **kwargs):
    raw_key = raw_input('user\'s key:')
    caption = raw_input('node\'s caption:')
    try:
        key, uid, url = raw_key.rsplit('$')
        cpu_number = multiprocessing.cpu_count()
        cpu_power = get_cpu_power()
        node_platform = platform.platform()
        try:
            link = Uplink(url)
            status, response = link.post('/rest/register',{'uid':uid,'key':key,'caption':caption, 'platform':node_platform, 'cpu_number':cpu_number, 'cpu_power':cpu_power })
        except:
            eject('connection error')
        if status == 500:
            f = open('logs/error.html', 'w')
            f.write(response)
            eject(str(status)+' server error, see logs/error.html for details')
        f = open('config/key.xml', 'w')
        f.write(response)
        print 'this node was registered successfully'
    except ValueError:
        eject('malformed key')

#####################################################################################
#Secondary functions
#####################################################################################
def eject(message):
    print message
    exit(-1)

def get_cpu_power():
    #f=open("/proc/cpuinfo")
    #for line in f:
    #    name, value = line.rsplit(':')
    #    if name.strip()=='cpu MHz':
    #        return value.strip()
    #return '-1'
    import bench
    return bench.run()